<template>
  <div style="margin-top: 50px">
    <el-form
      :model="value"
      ref="productAttrForm"
      label-width="120px"
      style="width: 720px"
      size="small"
    >
      <el-form-item
        v-for="(filterProductAttr, index) in filterProductAttrList"
        :label="index | filterLabelFilter"
        :key="filterProductAttr.key"
        @change="handleChange"
      >
        <div>商品规格：</div>
        <el-input
          v-model="filterProductAttr.value"
          @change="handleChange"
          style="width: 180px"
        >
        </el-input>
        <div>商品额外价格：</div>
        <el-input
          v-model="filterProductAttr.price"
          @change="handleChange"
          style="width: 180px"
        >
        </el-input>
        <br /><el-button
          style="margin-left: 20px"
          @click.prevent="removeFilterAttr(filterProductAttr)"
          @click="deletespecifications(filterProductAttr)"
          >删除</el-button
        >
      </el-form-item>

      <el-form-item>
        <el-button size="small" type="primary" @click="handleAddFilterAttr()"
          >新增</el-button
        >
      </el-form-item>

      <el-form-item label="商品相册：">
        <multi-upload
          v-model="selectProductPics"
          @DeletedImgs="DeletedImgs"
        ></multi-upload>
      </el-form-item>
      <el-form-item style="text-align: center">
        <el-button size="medium" @click="handlePrev"
          >上一步，填写商品促销</el-button
        >
        <el-button type="primary" size="medium" @click="handleNext"
          >完成，提交商品</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import MultiUpload from "@/components/Upload/multiUpload";
import {frozenspecifications} from "../../../../api/product";

export default {
  name: "ProductAttrDetail",
  components: { MultiUpload },
  props: {
    value: Object,
    isEdit: {
      type: Boolean,
      default: false,
    },
    getFilterProductAttrListData: [],
    getSelectProductPicsData: [],
  },
  data() {
    return {
      filterProductAttrList: [
        {
          value: "",
        },
      ],
      //编辑模式时是否初始化成功
      hasEditCreated: false,
      //商品属性分类下拉选项
      productAttributeCategoryOptions: [],
      //选中的商品属性
      selectProductAttr: [],
      //选中的商品参数
      selectProductParam: [],
      //选中的商品属性图片
      selectProductAttrPics: [],
      //可手动添加的商品属性
      addProductAttrValue: "",
      //商品富文本详情激活类型
      activeHtmlName: "pc",
    };
  },
  filters: {
    filterLabelFilter(index) {
      if (index === 0) {
        return "商品规格：";
      } else {
        return "";
      }
    },
  },
  computed: {
    //是否有商品属性图片
    hasAttrPic() {
      if (this.selectProductAttrPics.length < 1) {
        return false;
      }
      return true;
    },
    //商品的编号
    productId() {
      return this.value.id;
    },
    //商品的主图和画册图片
    selectProductPics: {
      get: function() {
        let pics = [];
        var list = [];
        this.getSelectProductPicsData.forEach((item) => {
          console.log(item);
          var line = item.imgPaht.indexOf("files") + 6;
          pics.push({
            url: "http://localhost:5000/" + item.imgPaht.slice(line),
            id: item.imgId,
            productId: item.id,
          });
          var res = {
            url: item.imgPaht,
            id: item.imgId,
            productId: item.id,
          };
          list.push(res);
        });
        this.$emit("setProductDetailImgs", list);
        return pics;
      },
      set: function(newValue) {
        console.log(newValue[0]);
        this.$emit("setProductDetailImgs", newValue[0]);
      },
    },
  },
  created() {
    if (this.isEdit) {
      this.filterProductAttrList = [];
      this.getFilterProductAttrListData.forEach((element) => {
        var res = {
          value: element.specificationsName,
          price: element.price,
          id: element.id
        };
        this.filterProductAttrList.push(res);
      });
      // console.log(this.filterProductAttrList);
      this.$emit("setFilterProductAttrList", this.filterProductAttrList);
    }
  },
  watch: {
    productId: function(newValue) {
      if (!this.isEdit) return;
      if (this.hasEditCreated) return;
      if (newValue === undefined || newValue == null || newValue === 0) return;
      this.handleEditCreated();
    },
    getFilterProductAttrListData: function() {
      if (this.isEdit) {
        this.filterProductAttrList = [];
        this.getFilterProductAttrListData.forEach((element) => {
          if (element.isActived) {
            var res = {
              value: element.specificationsName,
              price: element.price,
              id: element.id
            };
            this.filterProductAttrList.push(res);
          }
        });
        // console.log(this.filterProductAttrList);
        this.$emit("setFilterProductAttrList", this.filterProductAttrList);
      }
    },
  },
  methods: {
    deletespecifications(val){
      // console.log(val);
      console.log(val.id);
      frozenspecifications(val.id);
    },

    DeletedImgs(val) {
      // console.log(val);
      var res = [];
      res.push(val);
      this.$emit("getDeletedImgs", res);
    },
    //规格
    handleChange(val) {
      var res = this.filterProductAttrList;
      console.log(val);
      console.log(res);
      this.$emit("setFilterProductAttrList", res);
    },
    handleEditCreated() {
      //根据商品属性分类id获取属性和参数
      if (this.value.productAttributeCategoryId != null) {
        this.handleProductAttrChange(this.value.productAttributeCategoryId);
      }
      this.hasEditCreated = true;
    },
    getProductAttrCateList() {
      let param = { pageNum: 1, pageSize: 100 };
      // fetchProductAttrCateList(param).then((response) => {
      this.productAttributeCategoryOptions = [];
      let list = param;
      for (let i = 0; i < list.length; i++) {
        this.productAttributeCategoryOptions.push({
          label: list[i].name,
          value: list[i].id,
        });
      }
      // });
    },
    getProductAttrList(type, cid) {
      console.log(type, cid);
      let param = { pageNum: 1, pageSize: 100, type: type };
      // fetchProductAttrList(cid, param).then((response) => {
      let list = param;
      if (type === 0) {
        this.selectProductAttr = [];
        for (let i = 0; i < list.length; i++) {
          let options = [];
          let values = [];
          if (this.isEdit) {
            if (list[i].handAddStatus === 1) {
              //编辑状态下获取手动添加编辑属性
              options = this.getEditAttrOptions(list[i].id);
            }
            //编辑状态下获取选中属性
            values = this.getEditAttrValues(i);
          }
          this.selectProductAttr.push({
            id: list[i].id,
            name: list[i].name,
            handAddStatus: list[i].handAddStatus,
            inputList: list[i].inputList,
            values: values,
            options: options,
          });
        }
        if (this.isEdit) {
          //编辑模式下刷新商品属性图片
          this.refreshProductAttrPics();
        }
      } else {
        this.selectProductParam = [];
        for (let i = 0; i < list.length; i++) {
          let value = null;
          if (this.isEdit) {
            //编辑模式下获取参数属性
            value = this.getEditParamValue(list[i].id);
          }
          this.selectProductParam.push({
            id: list[i].id,
            name: list[i].name,
            value: value,
            inputType: list[i].inputType,
            inputList: list[i].inputList,
          });
        }
      }
      // });
    },
    //获取设置的可手动添加属性值
    getEditAttrOptions(id) {
      console.log(id);
      let options = [];
      for (let i = 0; i < this.value.productAttributeValueList.length; i++) {
        let attrValue = this.value.productAttributeValueList[i];
        if (attrValue.productAttributeId === id) {
          let strArr = attrValue.value.split(",");
          for (let j = 0; j < strArr.length; j++) {
            options.push(strArr[j]);
          }
          break;
        }
      }
      return options;
    },
    //获取选中的属性值
    getEditAttrValues(index) {
      console.log(index);
      let values = new Set();
      if (index === 0) {
        for (let i = 0; i < this.value.skuStockList.length; i++) {
          let sku = this.value.skuStockList[i];
          let spData = JSON.parse(sku.spData);
          if (spData != null && spData.length >= 1) {
            values.add(spData[0].value);
          }
        }
      } else if (index === 1) {
        for (let i = 0; i < this.value.skuStockList.length; i++) {
          let sku = this.value.skuStockList[i];
          let spData = JSON.parse(sku.spData);
          if (spData != null && spData.length >= 2) {
            values.add(spData[1].value);
          }
        }
      } else {
        for (let i = 0; i < this.value.skuStockList.length; i++) {
          let sku = this.value.skuStockList[i];
          let spData = JSON.parse(sku.spData);
          if (spData != null && spData.length >= 3) {
            values.add(spData[2].value);
          }
        }
      }
      return Array.from(values);
    },
    //获取属性的值
    getEditParamValue(id) {
      console.log(id);
      for (let i = 0; i < this.value.productAttributeValueList.length; i++) {
        if (id === this.value.productAttributeValueList[i].productAttributeId) {
          return this.value.productAttributeValueList[i].value;
        }
      }
    },
    handleProductAttrChange(value) {
      console.log(value);
      this.getProductAttrList(0, value);
      this.getProductAttrList(1, value);
    },
    getInputListArr(inputList) {
      console.log(inputList);
      return inputList.split(",");
    },
    handleRemoveProductAttrValue(idx, index) {
      console.log(idx, index);
      this.selectProductAttr[idx].options.splice(index, 1);
    },
    getProductSkuSp(row, index) {
      console.log(row, index);
      let spData = JSON.parse(row.spData);
      if (spData != null && index < spData.length) {
        return spData[index].value;
      } else {
        return null;
      }
    },
    refreshProductSkuList() {
      this.value.skuStockList = [];
    },
    
    refreshProductAttrPics() {
      this.selectProductAttrPics = [];
      if (this.selectProductAttr.length >= 1) {
        let values = this.selectProductAttr[0].values;
        for (let i = 0; i < values.length; i++) {
          let pic = null;
          if (this.isEdit) {
            //编辑状态下获取图片
            pic = this.getProductSkuPic(values[i]);
          }
          this.selectProductAttrPics.push({ name: values[i], pic: pic });
        }
      }
    },
    getOptionStr(arr) {
      console.log(arr);
      let str = "";
      for (let i = 0; i < arr.length; i++) {
        str += arr[i];
        if (i != arr.length - 1) {
          str += ",";
        }
      }
      return str;
    },
    handleRemoveProductSku(index, row) {
      console.log(index, row);
      console.log(row);
      let list = this.value.skuStockList;
      if (list.length === 1) {
        list.pop();
      } else {
        list.splice(index, 1);
      }
    },
    getParamInputList(inputList) {
      console.log(inputList);
      return inputList.split(",");
    },
    handlePrev() {
      this.$emit("prevStep");
    },
    handleNext() {
      // this.mergeProductAttrValue();
      // this.mergeProductAttrPics();
      this.$emit("finishCommit", this.isEdit);
    },
    handleAddFilterAttr() {
      if (this.filterProductAttrList.length === 10) {
        this.$message({
          message: "最多添加10个",
          type: "warning",
          duration: 1000,
        });
        return;
      }
      this.filterProductAttrList.push({
        value: null,
        key: Date.now(),
      });
    },
    removeFilterAttr(productAttributeId) {
      if (this.filterProductAttrList.length === 1) {
        this.$message({
          message: "至少要留一个",
          type: "warning",
          duration: 1000,
        });
        return;
      }
      var index = this.filterProductAttrList.indexOf(productAttributeId);
      if (index !== -1) {
        this.filterProductAttrList.splice(index, 1);
      }
    },
  },
};
</script>

<style scoped>
.littleMarginLeft {
  margin-left: 10px;
}

.littleMarginTop {
  margin-top: 10px;
}

.paramInput {
  width: 250px;
}

.paramInputLabel {
  display: inline-block;
  width: 100px;
  text-align: right;
  padding-right: 10px;
}

.cardBg {
  background: #f8f9fc;
}
</style>
